package com.leetcode.stack_queue;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author Dennis Li
 * @date 2020/8/2 15:09
 */
public class MaxSlidingWindow_239 {

    static class MonotonicQueue {
        Deque<Integer> queue;

        public void offer(int num) {
            //单调队列的 push ⽅法依然在 队尾添加元素，但是要把前⾯⽐新元素⼩的元素都删掉：
            // 如果有更大的加入，那么他之前加入的最小的肯定不会成为最大值，所以可以直接执行出队
            while (!queue.isEmpty() && num > queue.peekLast()) {
                queue.poll();
            }
            queue.offerLast(num);
        }

        public void poll(int num) {
            if (!queue.isEmpty() && num == queue.peek())
                queue.pollFirst();
        }

        public int max() {
            return queue.peek();
        }

        public MonotonicQueue(Deque<Integer> queue) {
            this.queue = queue;
        }
    }

    public int[] maxSlidingWindow(int[] nums, int k) {
        MonotonicQueue queue = new MonotonicQueue(new LinkedList<>());
        int len = nums.length;
        int[] res = new int[len - k + 1];
        for (int i = 0; i < len; i++) {
            if (i < k)
                queue.offer(nums[i]);
            else {
                queue.offer(nums[i]);
                res[i - k + 1] = queue.max();
                queue.poll(nums[i - k + 1]);
            }
        }
        return res;
    }

    static class Solution {

        static class MonotonicQueue {

            Deque<Integer> queue;

            public MonotonicQueue(Deque<Integer> queue) {
                this.queue = queue;
            }

            public void offer(int num) {
                while (!queue.isEmpty() && num > queue.peekLast())
                    queue.pollLast();
                queue.offerLast(num);
            }

            public void poll(int num) {
                if (num == queue.peekFirst())
                    queue.pollFirst();
            }

            public int max() {
                return queue.peek();
            }

        }

        public int[] maxSlidingWindow(int[] nums, int k) {
            MonotonicQueue queue = new MonotonicQueue(new LinkedList<>());
            int len = nums.length;
            int[] res = new int[len - k + 1];

            for (int i = 0; i < nums.length; i++) {
                if (i < k - 1)
                    queue.offer(nums[i]);
                else {
                    queue.offer(nums[i]);
                    res[i - k + 1] = queue.max();
                    queue.poll(nums[i - k + 1]);
                }
            }
            return res;
        }
    }

}
